#!/usr/bin/env python3
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

import base64
from pathlib import Path

import pytest

from cmk.utils.images import CMKImage, ImageSize, ImageType

TEST_PNG = base64.b64decode(
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAABhGlDQ1BJQ0MgcHJvZmlsZQAAKJF9"
    "kT1Iw0AcxV9bpSKtgnYQcchQnSyIijpqFYpQIdQKrTqYXPoFTRqSFBdHwbXg4Mdi1cHFWVcHV0EQ"
    "/ABxdnBSdJES/5cUWsR4cNyPd/ced+8Af73MVLNjDFA1y0gl4kImuyoEXxFAGD3ow7TETH1OFJPw"
    "HF/38PH1LsazvM/9OcJKzmSATyCeZbphEW8QT21aOud94ggrSgrxOfGoQRckfuS67PIb54LDfp4Z"
    "MdKpeeIIsVBoY7mNWdFQiSeJo4qqUb4/47LCeYuzWq6y5j35C0M5bWWZ6zSHkMAiliBCgIwqSijD"
    "QoxWjRQTKdqPe/gHHb9ILplcJTByLKACFZLjB/+D392a+YlxNykUBzpfbPtjGAjuAo2abX8f23bj"
    "BAg8A1day1+pAzOfpNdaWvQI6N0GLq5bmrwHXO4AA0+6ZEiOFKDpz+eB9zP6pizQfwt0r7m9Nfdx"
    "+gCkqavkDXBwCIwUKHvd491d7b39e6bZ3w91SHKogOdbRwAAAAlwSFlzAAAuIwAALiMBeKU/dgAA"
    "AAd0SU1FB+gDDQ4TN1DFWNUAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAA"
    "DElEQVQI12NQuaECAAJEASHPE+sZAAAAAElFTkSuQmCC"
)
TEST_JPG = base64.b64decode(
    "/9j/4AAQSkZJRgABAQEBLAEsAAD/4QfURXhpZgAASUkqAAgAAAAHAA4BAgASAAAAYgAAABoBBQAB"
    "AAAAdAAAABsBBQABAAAAfAAAACgBAwABAAAAA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AAAAAAD/2gAIAQMBAT8Qf//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Q"
    "f//EABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEAAT8Qf//Z"
)

TEST_ICO = base64.b64decode(
    "AAABAAEAAQECAAEAAQA4AAAAFgAAACgAAAABAAAAAgAAAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAA"
    "AAAAAAAk2CQAAAAAAAAAAAAAAAAA"
)


def test_image_loading_png() -> None:
    image = CMKImage(TEST_PNG, ImageType.PNG)
    assert image.image_size() == ImageSize(1, 1)
    assert image.get_comment() == "Created with GIMP"
    with pytest.raises(ValueError):
        CMKImage(TEST_PNG, ImageType.JPG)


def test_image_loading_jpg() -> None:
    image = CMKImage(TEST_JPG, ImageType.JPG)
    assert image.image_size() == ImageSize(1, 1)
    with pytest.raises(ValueError):
        CMKImage(TEST_JPG, ImageType.PNG)


def test_image_loading_jpg_and_png() -> None:
    assert CMKImage(TEST_JPG, [ImageType.JPG, ImageType.PNG]).image_size() == ImageSize(1, 1)
    assert CMKImage(TEST_PNG, [ImageType.JPG, ImageType.PNG]).image_size() == ImageSize(1, 1)
    with pytest.raises(ValueError):
        CMKImage(TEST_ICO, [ImageType.PNG, ImageType.JPG])


def test_metadata(tmp_path: Path) -> None:
    path = tmp_path / "test.png"
    image = CMKImage(TEST_JPG, ImageType.JPG)
    image.add_metadata("Comment", "Test")
    image.save(path, ImageType.PNG)

    image = CMKImage.from_path(path, ImageType.PNG)
    assert image.get_comment() == "Test"
